﻿package net.wangit.dev.table;

import java.util.HashMap;
import java.util.Map;

import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.context.LocalContext;
import net.wangit.dev.BeanEnumerationHelper;
import net.wangit.dev.ConsoleDomainUtil;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.util.DBHelper;
import net.wangit.support.MapListFactory;
import net.wangit.util.Checker;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class GCMapListFactory implements MapListFactory {

	private static final Log log = LogFactory
			.getLog(net.wangit.dev.table.GCMapListFactory.class);
	private static final Map<String, String> AUTO_BY_DB_MAP;
	private static final String SQL = "select iid,n from INCREMENTOR order by o";

	public GCMapListFactory() {
	}

	public MapList getMapList() {
		MapList result = BeanEnumerationHelper.getEnumeration("generator");
		result.insertRow(0, AUTO_BY_DB_MAP);
		try {
			net.wangit.context.ActionContext ac = LocalContext
					.getLocalContext().getActionContext();
			String domain = ConsoleDomainUtil.getDomain(ac);
			DB db = DBHelper.getDomainDB(domain);
			MapList incrementors = db.query(GCMapListFactory.SQL);
			if (!Checker.isEmpty(incrementors)) {
				int index = result.size();
				for (int i = 0; i < incrementors.size(); i++) {
					Row row = incrementors.getRow(i);
					String id = row.get("iid");
					String name = row.get("n");
					if (Checker.isEmpty(name))
						name = (new StringBuilder("(")).append(id).append(")")
								.toString();
					result.put(index, "value", id);
					result.put(index, "name", name);
					index++;
				}

			}
		} catch (Exception e) {
			log.error((new StringBuilder(
					"create Incrementor Enumeration failed:")).append(e));
		}
		return result;
	}

	static {
		AUTO_BY_DB_MAP = new HashMap<String, String>();
		AUTO_BY_DB_MAP.put("value", "0");
		AUTO_BY_DB_MAP.put("name", "$L{components:generator.0}");
	}
}
